import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 信号量：实现限流
 */
public class SemaphoreDemo1 {
    public static void main(String[] args) {
        //创建线程池
        ExecutorService service= Executors.newFixedThreadPool(5);
        //创建信号量
        Semaphore semaphore=new Semaphore(2);
        //统一任务定义
        Runnable runnable=new Runnable() {
            @Override
            public void run() {
                Thread currThread=Thread.currentThread();//得到执行此任务的线程
                System.out.println("进入线程:"+currThread.getName());
                try {
                    semaphore.acquire();//如果没有可用令牌的话，那么线程会阻塞在当前位置
                    System.out.println(currThread.getName()+
                            ":得到了令牌|Time"+ LocalDateTime.now());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    System.out.println(currThread.getName()+
                            ":释放了令牌|Time"+ LocalDateTime.now());
                    semaphore.release();
                }
            }
        };

        //定义新线程执行任务
        service.submit(runnable);
        //定义新线程执行任务
        service.submit(runnable);
        //定义新线程执行任务
        service.submit(runnable);
        //定义新线程执行任务
        service.submit(runnable);
        //定义新线程执行任务
        service.submit(runnable);


    }
}
